import sys
from Ui_win_S1 import Ui_Form
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QComboBox, QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox, QApplication, QWidget
from PyQt5 import QtGui
from PyQt5.QtCore import QTimer
import os
from com import Communicate, SerialThread
import datetime
import tkinter
import tkinter.ttk
import ctypes
from agEncode import AgEncode
from pyAgDongle import PyAgDongle2
import logger
from settings import DongleConfig
from pywin32evtlog import mSysEvent

# 获取当前脚本的绝对路径
script_dir = os.path.dirname(os.path.abspath(__file__))
# 构建配置文件的路径
icon_file_path = os.path.join(script_dir, 'icon')

# 使用软件前检验授权码
class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setWindowTitle('授权码验证')
        self.setFixedSize(400, 200)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.label = QLabel('机器码：')
        self.layout.addWidget(self.label)

        self.lineEdit1 = QLineEdit()
        # self.lineEdit1.setText('test1')
        self.lineEdit1.setReadOnly(True)
        self.layout.addWidget(self.lineEdit1)

        self.label = QLabel('机器ID：')
        self.layout.addWidget(self.label)

        self.lineEdit2 = QLineEdit()
        # self.lineEdit2.setText('test2')
        self.lineEdit2.setReadOnly(True)
        self.layout.addWidget(self.lineEdit2)

        self.label = QLabel('请输入授权码：')
        self.layout.addWidget(self.label)

        self.lineEdit = QLineEdit()
        self.layout.addWidget(self.lineEdit)

        self.buttonLayout = QHBoxLayout()
        self.okButton = QPushButton('确定')
        self.cancelButton = QPushButton('取消')
        self.buttonLayout.addWidget(self.okButton)
        self.buttonLayout.addWidget(self.cancelButton)
        self.layout.addLayout(self.buttonLayout)

        self.okButton.clicked.connect(self.check_license)
        self.cancelButton.clicked.connect(self.reject)

        # self.agDongle2 = PyAgDongle()
        # self.init_dongle2()

    #     self.check_time()

    # def check_time(self):
    #     print('check_time--------')
    #     # 获取今天的日期和时间
    #     now = datetime.datetime.now()
    #     today_end = datetime.datetime(now.year, now.month, now.day, 13, int('14'), 59)
    #     # today_end = datetime.datetime(now.year, now.month, now.day, 23, 59, 59)

    #     # 如果当前时间已经超过今天结束的时间，则立即弹出提示框
    #     if now >= today_end and not self.time_expired_dialog_shown:
    #         self.time_expired_dialog_shown = True
    #         self.serial_thread.stop()  # 停止串口线程
    #         print(f"1停止串口线程")
    #         print(f"1使用权限已到期，请联系管理员！")
    #         try:
    #             self.timer.stop()
    #         except:
    #             pass
    #         self.show_time_expired_dialog()
    #         self.time_expired_dialog_shown = True
    #         # reply = QMessageBox.critical(self,
    #         #                              '权限到期提示',
    #         #                              '使用权限已到期，请连续管理员！',
    #         #                              QMessageBox.Ok)  # 使用Ok按钮作为唯一的按钮

    #         # # 连接OK按钮的点击事件到槽函数，以便关闭程序
    #         # reply.buttons()[0].clicked.connect(self.close_application)

    
    #     else:
    #         # 设置定时器，每分钟检查一次时间
    #         self.timer = QTimer(self)
    #         self.timer.timeout.connect(self.check_time)
    #         self.timer.start(10000)  # 60000 毫秒 = 1 分钟

    # def show_time_expired_dialog(self):
        # 显示模态对话框        
        # msgBox = QMessageBox.critical(self, '权限到期提示', '使用权限已到期，请连续管理员！', QMessageBox.Ok)

        # # 检查用户是否点击了“OK”
        # if msgBox == QMessageBox.Ok:
        #     # 用户点击了“OK”，退出程序
        #     QApplication.instance().quit()
        #     print('close dia')
        #     return

    def init_dongle2(self):
        self.agDongle2.py_agCreateCAgDongle2()
        machine_code,machine_ID = self.agDongle2.py_agGenerateMRCode_DR2()
        self.lineEdit1.setText(str(machine_code))
        self.lineEdit2.setText(str(machine_ID))


    def check_license(self):
        # 判断给的时间是否超过，超过就不accept()
        self.accept()
        # license_key = self.lineEdit.text()
        # r = self.agDongle2.py_agActivateSoftware2(license_key)
        # if r >= 0:
        #     self.accept()
        # else:
        #     QMessageBox.warning(self, '错误', f'授权码无效，请重新输入！错误码：{r}')

        # 这里判断是否有加密狗，没有就验证授权码，有就直接进
        # if self.validate_license(license_key):
        #     self.accept()
        # else:
        #     QMessageBox.warning(self, '错误', '授权码无效，请重新输入！')

    # def validate_license(self, license_key):
    #     # 这里添加授权码验证逻辑，以下为示例
    #     valid_key = '1'  # 假设的有效授权码
    #     return license_key == valid_key

class EquipmentMaintenanceApp(QWidget, Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.serial_thread = SerialThread()
        self.communicate = Communicate()        
        self.comboBox.addItems(self.serial_thread.com_search())  
        self.comboBox.setCurrentText(dongle_cfg.port)
        self.textEdit.setReadOnly(True) 
        self.encoder = AgEncode()
        self.logger = logger.logger_config(log_path='run_log.log', logging_name='运行日志')
        self.log_frame = logger.logger_config(log_path='frame.log', logging_name='帧日志')
        self.timer = None

        #指示灯初始化
        self.light_init()

        #信号槽
        self.pushButton.clicked.connect(self.on_open_clicked)
        self.pushButton_2.clicked.connect(self.on_close_clicked)
        self.pushButton_3.clicked.connect(self.on_highV_power_clicked)
        self.pushButton_4.clicked.connect(self.on_highV_PCBA_clicked)
        self.pushButton_5.clicked.connect(self.on_highV_correct_clicked)
        self.pushButton_6.clicked.connect(self.on_sport_power_clicked)
        self.pushButton_7.clicked.connect(self.on_sport_PCBA_clicked)
        self.pushButton_8.clicked.connect(self.on_sport_correct_clicked)
        self.comboBox.setEditable(False)  # 设置为不可编辑
        self.comboBox.popupShown.connect(self.on_combobox_popup_shown)
        self.serial_thread.data_received.connect(self.on_data_received)
        self.time_expired_dialog_shown = False  # 添加一个标志变量
        self.get_expired_date()
        self.check_time()
        

    # def check_time(self):
    #     self.logger.info('--------1分钟检查一次授权期限--------')
    #     now = datetime.datetime.now()
    #     # 如果当前时间已经超过今天结束的时间，则立即弹出提示框
    #     if now >= self.expire_date and not self.time_expired_dialog_shown:
    #         self.time_expired_dialog_shown = True
    #         self.serial_thread.stop()  # 停止串口线程
    #         self.log_update(f"停止串口线程")
    #         self.log_update(f"使用权限已到期，请联系管理员！")
    #         try:
    #             self.timer.stop()
    #         except:
    #             pass
    #         self.show_time_expired_dialog()
    #         self.time_expired_dialog_shown = True
    
    #     else:
    #         # 设置定时器，每分钟检查一次时间
    #         self.timer = QTimer(self)
    #         self.timer.timeout.connect(self.check_time)
    #         self.timer.start(60000)  # 60000 毫秒 = 1 分钟
    def check_time(self):
        self.logger.info('--------1分钟检查一次授权期限--------')
        now = datetime.datetime.now()
        # 如果当前时间已经超过今天结束的时间，则立即弹出提示框
        if now >= self.expire_date and not self.time_expired_dialog_shown:
            self.time_expired_dialog_shown = True
            self.serial_thread.stop()  # 停止串口线程
            self.log_update(f"停止串口线程")
            self.log_update(f"使用权限已到期，请联系管理员！")
            if self.timer is not None:
                self.timer.stop()
                self.timer.deleteLater()  # 确保定时器被正确删除
            self.show_time_expired_dialog()
        
        else:
            # 确保定时器被停止并删除，避免重复创建
            if self.timer is not None:
                self.timer.stop()
                self.timer.deleteLater()
            self.timer = QTimer(self)
            self.timer.timeout.connect(self.check_time)
            self.timer.start(60000)  # 60000 毫秒 = 1 分钟



    def show_time_expired_dialog(self):     
        msgBox = QMessageBox.critical(self, '权限到期提示', '使用权限已到期，请联系管理员！', QMessageBox.Ok)

        if msgBox == QMessageBox.Ok:
            # 用户点击了“OK”，退出程序
            QApplication.instance().quit()
            print('close expired dialog')
            return
    
    def light_init(self):
        self.label_3.hide()
        self.label_4.hide()
        self.label_5.hide()
        self.label_6.hide()
        self.label_7.hide()
        self.label_8.hide()
        self.label_9.hide()

    def on_open_clicked(self):
        # 打开串口
        if self.serial_thread.ser.is_open:
            self.serial_thread.ser.close()
            self.log_update(f"串口 {self.serial_thread.ser.port} 已经开启，已将其关闭")
        if self.serial_thread.open_port(self.comboBox.currentText(), dongle_cfg.baudrate):
            self.label_4.hide()
            self.label_5.hide()
            self.label_6.hide()
            self.label_7.hide()
            self.label_8.hide()
            self.label_9.hide()

            self.label_3.show()
            self.label_2.hide()
            self.log_update(f"串口 {self.serial_thread.ser.port} 打开完成")
            # 启动串口线程
            self.serial_thread.start()
        else:
            self.log_update(f"串口 {self.serial_thread.ser.port} 打开失败！")
            self.label_2.show()
            self.label_3.hide()
            self.label_4.hide()
            self.label_5.hide()
            self.label_6.hide()
            self.label_7.hide()
            self.label_8.hide()
            self.label_9.hide()
        dongle_cfg.save_port(self.serial_thread.ser.port)

    def on_close_clicked(self):
        if self.serial_thread.ser.is_open:
            # self.serial_thread.ser.close()
            self.serial_thread.stop()
            self.label_2.show()
            self.label_3.hide()
            self.log_update(f"串口 {self.serial_thread.ser.port} 关闭")
        else:
            self.log_update(f"串口 {self.serial_thread.ser.port} 已经关闭")
         
    def update_ui(self):        
        self.comboBox.addItems(self.ports)

    def log_update(self,text):
        # 移动光标到文档末尾并插入新行
        # cursor = self.textEdit.textCursor()
        # cursor.movePosition(QCursor.End)
        # cursor.insertText("\n")  # 插入一个换行符
        # text_edit.setTextCursor(cursor)  # 设置新的光标位置
        # 移动光标到最下方新的一行
        self.textEdit.moveCursor(QtGui.QTextCursor.End)
        self.textEdit.ensureCursorVisible()
        print(f"{text}")
        self.textEdit.insertPlainText(f"[{self.getNow()}] {text}\r\n")
        self.textEdit.ensureCursorVisible()
        self.logger.info(text)

    def on_combobox_popup_shown(self):
        items = self.serial_thread.com_search()
        if len(items) == 0:
            self.log_update('查询串口数为0')
            return
        else:
            self.comboBox.clear()
            self.comboBox.addItems(items)
            self.comboBox.setCurrentText(self.serial_thread.ser.port)
            self.log_update('查询串口')

    def read_command(self, command, data_list):
        """
        识别收到的命令类型，只回复激活请求
        """
        #查询激活状态命令
        if command == 0xF8:
            #查询运动主控板激活状态
            if data_list[0] == 0x00:
                #上电启动校验
                if data_list[1] == 0x00:
                    if data_list[2] == 0x01:
                        self.log_update(f"查询运动主控板上电校验状态：已激活！")
                        self.label_7.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\g-30.png"))
                        self.label_7.show()
                    else:
                        self.log_update(f"查询运动主控板上电校验状态：未激活！")
                        self.label_7.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\red-30.png"))
                        self.label_7.show()
                #PCBA烧录程序后的校验
                if data_list[1] == 0x01:        
                    if data_list[2] == 0x01:
                        self.log_update(f"查询运动主控板PCBA校验状态：已激活！")
                        self.label_8.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\g-30.png"))
                        self.label_8.show()
                    else:
                        self.log_update(f"查询运动主控板PCBA校验状态：未激活！")
                        self.label_8.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\red-30.png"))
                        self.label_8.show()
                #需要校正时候的校验
                if data_list[1] == 0x02:    
                    if data_list[2] == 0x01:
                        self.log_update(f"查询运动主控板校正校验状态：已激活！")
                        self.label_9.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\g-30.png"))
                        self.label_9.show()
                    else:
                        self.log_update(f"查询运动主控板校正校验状态：未激活！")
                        self.label_9.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\red-30.png"))
                        self.label_9.show()

            #查询高压主控板激活状态
            if data_list[0] == 0x01:
                #上电启动校验
                if data_list[1] == 0x00:
                    if data_list[2] == 0x01:
                        self.log_update(f"查询高压主控板上电校验状态：已激活！")
                        self.label_4.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\g-30.png"))
                        self.label_4.show()
                    else:
                        self.log_update(f"查询高压主控板上电校验状态：未激活！")
                        self.label_4.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\red-30.png"))
                        self.label_4.show()
                #PCBA烧录程序后的校验
                if data_list[1] == 0x01:        
                    if data_list[2] == 0x01:
                        self.log_update(f"查询高压主控板PCBA校验状态：已激活！")
                        self.label_5.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\g-30.png"))
                        self.label_5.show()
                    else:
                        self.log_update(f"查询高压主控板PCBA校验状态：未激活！")
                        self.label_5.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\red-30.png"))
                        self.label_5.show()
                #需要校正时候的校验
                if data_list[1] == 0x02:    
                    if data_list[2] == 0x01:
                        self.log_update(f"查询高压主控板校正校验状态：已激活！")
                        self.label_6.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\g-30.png"))
                        self.label_6.show()
                    else:
                        self.log_update(f"查询高压主控板校正校验状态：未激活！")
                        self.label_6.setPixmap(QtGui.QPixmap(f"{icon_file_path}\\red-30.png"))
                        self.label_6.show()       
            
            #查询其他状态
            if data_list[0] == 0x02:
                #上电启动校验
                if data_list[1] == 0x00:
                    pass
                #PCBA烧录程序后的校验
                if data_list[1] == 0x01:        
                    pass
                #需要校正时候的校验
                if data_list[1] == 0x02:    
                    pass               

        #动态校验命令(CMD_DYNA_VERIF_PCBA)
        #从PCBA(下位机)发出的动态校验命令
        if command == 0xFA:
            random_data = [0x00, 0x00, 0x00, 0x00]
            #运动主控板激活
            if data_list[0] == 0x00:
                #上电校验
                if data_list[1] == 0x00:
                    self.log_update(f"运动主控板上电启动校验请求激活！！！")
                    #解析随机码
                    for i in range(4):                      
                       random_data[i] = data_list[2+i]
                       print(f"randomdata:{random_data[i]}")
                    #调用加密算法生成动态码
                    encode_data = self.encoder.ag_encode(random_data)
                    print(f"encodedata:{hex(encode_data[0])} {hex(encode_data[1])} {hex(encode_data[2])} {hex(encode_data[3])}")
                    #组帧发送
                    data_frame = self.serial_thread.build_frame(0xFA, [0x00, 0x00, encode_data[0], encode_data[1], encode_data[2], encode_data[3], 0xF0])
                    self.serial_thread.write_data(data_frame)
                    self.log_update("下发运动主控板上电激活密钥")
                    # self.log_update(f"Send: {data_frame.hex()}")
                #PCBA校验
                if data_list[1] == 0x01:        
                    self.log_update(f"运动主控板PCBA校验请求激活！！！")
                    
                    for i in range(4):                      
                       random_data[i] = data_list[2+i]
                       print(f"randomdata:{random_data[i]}")
                    
                    encode_data = self.encoder.ag_encode(random_data)
                    print(f"encodedata:{hex(encode_data[0])} {hex(encode_data[1])} {hex(encode_data[2])} {hex(encode_data[3])}")
                    
                    data_frame = self.serial_thread.build_frame(0xFA, [0x00, 0x01, encode_data[0], encode_data[1], encode_data[2], encode_data[3], 0xF0])
                    self.serial_thread.write_data(data_frame)
                    self.log_update("下发运动主控板PCBA激活密钥")
                    # self.log_update(f"Send: {data_frame.hex()}")
                #校正校验
                if data_list[1] == 0x02:    
                    self.log_update(f"运动主控板校正校验请求激活！！！")  
                    for i in range(4):                      
                       random_data[i] = data_list[2+i]
                       print(f"randomdata:{random_data[i]}")
                    
                    encode_data = self.encoder.ag_encode(random_data)
                    print(f"encodedata:{hex(encode_data[0])} {hex(encode_data[1])} {hex(encode_data[2])} {hex(encode_data[3])}")
                    
                    data_frame = self.serial_thread.build_frame(0xFA, [0x00, 0x02, encode_data[0], encode_data[1], encode_data[2], encode_data[3], 0xF0])
                    self.serial_thread.write_data(data_frame)
                    self.log_update("下发运动主控板校正激活密钥")     
                    # self.log_update(f"Send: {data_frame.hex()}")    
            #高压主控板激活
            if data_list[0] == 0x01:
                #上电校验
                if data_list[1] == 0x00:
                    self.log_update(f"高压主控板上电启动校验请求激活！！！")
                    for i in range(4):                      
                       random_data[i] = data_list[2+i]
                       print(f"randomdata:{random_data[i]}")
                    
                    encode_data = self.encoder.ag_encode(random_data)
                    print(f"encodedata:{hex(encode_data[0])} {hex(encode_data[1])} {hex(encode_data[2])} {hex(encode_data[3])}")
                    
                    data_frame = self.serial_thread.build_frame(0xFA, [0x01, 0x00, encode_data[0], encode_data[1], encode_data[2], encode_data[3], 0xF0])
                    self.serial_thread.write_data(data_frame)
                    self.log_update("下发高压主控板上电激活密钥")     
                    # self.log_update(f"Send: {data_frame.hex()}")
                #PCBA校验
                if data_list[1] == 0x01:        
                    self.log_update(f"高压主控板PCBA校验请求激活！！！")
                    for i in range(4):                      
                       random_data[i] = data_list[2+i]
                       print(f"randomdata:{random_data[i]}")
                    
                    encode_data = self.encoder.ag_encode(random_data)
                    print(f"encodedata:{hex(encode_data[0])} {hex(encode_data[1])} {hex(encode_data[2])} {hex(encode_data[3])}")
                    
                    data_frame = self.serial_thread.build_frame(0xFA, [0x01, 0x01, encode_data[0], encode_data[1], encode_data[2], encode_data[3], 0xF0])
                    self.serial_thread.write_data(data_frame)
                    self.log_update("下发高压主控板PCBA激活密钥")     
                    # self.log_update(f"Send: {data_frame.hex()}")
                #校正校验
                if data_list[1] == 0x02:    
                    self.log_update (f"高压主控板校正校验请求激活！！！") 
                    for i in range(4):                      
                       random_data[i] = data_list[2+i]
                       print(f"randomdata:{random_data[i]}")
                    
                    encode_data = self.encoder.ag_encode(random_data)
                    print(f"encodedata:{hex(encode_data[0])} {hex(encode_data[1])} {hex(encode_data[2])} {hex(encode_data[3])}")
                    
                    data_frame = self.serial_thread.build_frame(0xFA, [0x01, 0x02, encode_data[0], encode_data[1], encode_data[2], encode_data[3], 0xF0])
                    self.serial_thread.write_data(data_frame)
                    self.log_update("下发高压主控板校正激活密钥")    
                    # self.log_update(f"Send: {data_frame.hex()}")
            


    def on_highV_power_clicked(self):
        """
        查询高压主控板上电激活状态：
        """
        if self.serial_thread.ser.is_open:
            data_frame = self.serial_thread.build_frame(0xF8, [0x01, 0x00, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0])
            self.serial_thread.write_data(data_frame)
            self.log_update("查询高压主控板上电激活状态......")
            self.log_update(f"Send: {data_frame.hex()}")
        else:
            self.log_update("串口未打开！")

    def on_highV_PCBA_clicked(self):
        """
        查询高压主控板PCBA激活状态：
        """
        if self.serial_thread.ser.is_open:
            data_frame = self.serial_thread.build_frame(0xF8, [0x01, 0x01, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0])
            self.serial_thread.write_data(data_frame)
            self.log_update("查询高压主控板PCBA激活状态......")
            self.log_update(f"Send: {data_frame.hex()}")
        else:
            self.log_update("串口未打开！")

    def on_highV_correct_clicked(self):
        """
        查询高压主控板校正激活状态：
        """
        if self.serial_thread.ser.is_open:
            data_frame = self.serial_thread.build_frame(0xF8, [0x01, 0x02, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0])
            self.serial_thread.write_data(data_frame)
            self.log_update("查询高压主控板校正激活状态......")
            self.log_update(f"Send: {data_frame.hex()}")
        else:
            self.log_update("串口未打开！")

    def on_sport_power_clicked(self):
        """
        查询运动主控板上电激活状态：
        """
        if self.serial_thread.ser.is_open:
            data_frame = self.serial_thread.build_frame(0xF8, [0x00, 0x00, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0])
            self.serial_thread.write_data(data_frame)
            self.log_update("查询运动主控板上电激活状态......")
            self.log_update(f"Send: {data_frame.hex()}")
        else:
            self.log_update("串口未打开！")

    def on_sport_PCBA_clicked(self):
        """
        查询运动主控板PCBA激活状态：
        """
        if self.serial_thread.ser.is_open:
            data_frame = self.serial_thread.build_frame(0xF8, [0x00, 0x01, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0])
            self.serial_thread.write_data(data_frame)
            self.log_update("查询运动主控板PCBA激活状态......")
            self.log_update(f"Send: {data_frame.hex()}")
        else:
            self.log_update("串口未打开！")

    def on_sport_correct_clicked(self):
        """
        查询运动主控板校正激活状态：
        """
        if self.serial_thread.ser.is_open:
            data_frame = self.serial_thread.build_frame(0xF8, [0x00, 0x02, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0])
            self.serial_thread.write_data(data_frame)
            self.log_update("查询运动主控板校正激活状态......")
            self.log_update(f"Send: {data_frame.hex()}")
        else:
            self.log_update("串口未打开！")

    def on_data_received(self, data):
        # if data[0] == 0xAA:
        #     if data[1] == 0xFA or data[1] == 0xF8:
        self.log_update(f"Received: {data.hex()}")
        # self.log_frame.info(f"Received: {data.hex()}")
        try:
            command, data_list, is_valid = self.serial_thread.parse_frame(data)
            # self.log_update(f"Parsed Command: {command}, Data: {data_list}, Checksum Valid: {is_valid}")


            if is_valid:
                self.read_command(command, data_list)
                print('is_valid')
            else:
                self.log_update(f"校验和错误！")

        except ValueError as e:
            self.log_update(f"Failed to parse data: {e}")

    def getNow(self):
        # 获取当前时间
        current_time = datetime.datetime.now()
        # 格式化时间，包含毫秒
        formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:23]
        return formatted_time
    
    def closeEvent(self, event):
        self.serial_thread.stop()  # 停止串口线程
        super().closeEvent(event)    
        self.log_update(f"停止串口线程，软件关闭")

    def get_expired_date(self):
        now = datetime.datetime.now()
        self.expire_date = now + datetime.timedelta(days=dongle_cfg.Validate)
        self.expire_date = self.expire_date.replace(hour=23, minute=59, second=59)
        self.log_update(f'授权期限：{self.expire_date.strftime("%Y-%m-%d %H:%M:%S")}')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    dongle_cfg = DongleConfig()
    log_main = logger.logger_config(log_path='main.log', logging_name='main主程序日志')
    e = mSysEvent()
    if not e.sysTime_is_modified():
        try:
            if dongle_cfg.is_hardDongle():
                    if dongle_cfg.check_hardDongle_validate():   
                        ex = EquipmentMaintenanceApp()
                        ex.show() 
                    else:
                        # pass
                        sys.exit(0)  # 如果加密狗未通过，退出程序
            else:
                dongle_cfg.init_dongle2()
                if dongle_cfg.check_dongle2_validate():
                    ex = EquipmentMaintenanceApp()
                    ex.show()
                else:
                    # pass
                    sys.exit(0)  # 如果加密狗未通过，退出程序
            # ex = EquipmentMaintenanceApp()
            # ex.show() 
            sys.exit(app.exec_())              
        except OSError as e:
            log_main.error("主程序异常中止！")
            print(e)
        finally:
            dongle_cfg.delete_dongles()
    else:
        log_main.error(f'软件已被禁止使用，错误码-3，请联系管理员！')
        QMessageBox.warning(None, '错误', f'软件已被禁止使用，错误码-3，请联系管理员！')
